//
//  JKWebViewViewController.m
//  JKBao
//
//  Created by 初程程 on 16/9/21.
//  Copyright © 2016年 初程程. All rights reserved.
//

#import "YLCWebViewViewController.h"
#import "YLCNavigationViewController.h"
#define PROGRESSTINTCOLOR [UIColor colorWithRed:89.0f / 255.0f green:12.0f / 255.0f blue:4.0f / 255.0f alpha:1.0f]
@interface YLCWebViewViewController ()<NJKWebViewProgressDelegate>

@end

@implementation YLCWebViewViewController
{
    NJKWebViewProgress*webViewProgress;
    UIProgressView* progressView;
    UIWebView* webContentView;
}
+ (void)showShareWebViewWithRequest:(NSURLRequest *)request
                           navTitle:(NSString *)title
                           shareUrl:(NSString *)shareUrl
                       shareContent:(NSString *)shareContent
                      shareImageUrl:(NSString *)shareImageUrl
                            isModel:(BOOL)isModel
                               from:(UIViewController *)controller{
    YLCWebViewViewController *con = [[YLCWebViewViewController alloc] init];
    con.isModel = isModel;
    con.navTitle = title;
    YLCAccountModel *userModel = [[YLCAccountManager shareManager] currentAccount];
    
    NSURL *url = request.URL;
    NSString *path = url.absoluteString;
    if (![url.absoluteString containsString:@"fromapp_user_id"]) {
        path = [NSString stringWithFormat:@"%@/fromapp_user_id/%@",path,userModel.user_id];
    }
    con.request = [NSURLRequest requestWithURL:[NSURL URLWithString:path]];
    con.shareImageUrl = shareImageUrl;
    con.shareContent = shareContent;
    con.shareUrl = shareUrl;
    con.isShare = YES;

    if (isModel) {
        YLCNavigationViewController *nav = [[YLCNavigationViewController alloc] initWithRootViewController:con];
        [controller presentViewController:nav animated:YES completion:nil];
    }else {
        [controller.navigationController pushViewController:con animated:YES];
    }

}
+ (void)showWebViewWithRequest:(NSURLRequest *)request
                      navTitle:(NSString *)title
                       isModel:(BOOL)isModel
                          from:(UIViewController *)controller {
    YLCWebViewViewController *con = [[YLCWebViewViewController alloc] init];
    con.isModel = isModel;
    con.navTitle = title;
    YLCAccountModel *userModel = [[YLCAccountManager shareManager] currentAccount];
    
    NSURL *url = request.URL;
    NSString *path = url.absoluteString;
    if (![url.absoluteString containsString:@"fromapp_user_id"]) {
        path = [NSString stringWithFormat:@"%@/fromapp_user_id/%@",path,userModel.user_id];
    }
    con.request = [NSURLRequest requestWithURL:[NSURL URLWithString:path]];
    
    if (isModel) {
        YLCNavigationViewController *nav = [[YLCNavigationViewController alloc] initWithRootViewController:con];
        [controller presentViewController:nav animated:YES completion:nil];
    }else {
        [controller.navigationController pushViewController:con animated:YES];
    }
}
+ (void)showWebViewWithContent:(NSString *)content
                      navTitle:(NSString *)title
                       isModel:(BOOL)isModel
                          from:(UIViewController *)controller {
    YLCWebViewViewController *con = [[YLCWebViewViewController alloc] init];
    con.isModel = isModel;
    con.content = content;
    con.navTitle = title;
    
    if (isModel) {
        YLCNavigationViewController *nav = [[YLCNavigationViewController alloc] initWithRootViewController:con];
        [controller presentViewController:nav animated:YES completion:nil];
    }else {
        [controller.navigationController pushViewController:con animated:YES];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = YLC_COMMON_BACKCOLOR;
    webViewProgress=[[NJKWebViewProgress alloc] init];
    webViewProgress.progressDelegate=self;
    webViewProgress.currentController = self;
    [self customSubViews];
    
}

- (void)customSubViews {
    
    progressView=[[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
    progressView.frame=CGRectMake(0, 0, self.view.frame.size.width,5);
    progressView.progressTintColor=PROGRESSTINTCOLOR;
    
    webContentView = [[UIWebView alloc] initWithFrame:CGRectMake(0,3, self.view.frame.size.width, self.view.frame.size.height-3)];
    webContentView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    webContentView.delegate = webViewProgress;
    [self.view addSubview:webContentView];
    [self.view addSubview:progressView];
    
    if (self.request) {
        
        [webContentView loadRequest:self.request];
        webContentView.frame=self.view.bounds;
        
    }else if (!JK_IS_STR_NIL(self.content)) {
        progressView.hidden=YES;
        webContentView.frame=self.view.bounds;
        [webContentView loadHTMLString:self.content baseURL:nil];
    }
}
- (UIBarButtonItem*)leftBarButtonItem{
    
    UIView *barView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 0, 40, 40);
    backBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [backBtn setImage:[UIImage imageNamed:@"back_white"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
//    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [barView addSubview:backBtn];
    
//    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    closeBtn.frame = CGRectMake(backBtn.frameMaxY+10, 0, 35, 40);
//    closeBtn.titleLabel.font = [UIFont systemFontOfSize:16];
//    [closeBtn addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];
//    [closeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [closeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
//    [closeBtn setTitle:@"关闭" forState:UIControlStateNormal];
//    [barView addSubview:closeBtn];
    
    return [[UIBarButtonItem alloc]initWithCustomView:barView];
}
- (UIBarButtonItem *)rightBarButtonItem{
    if (self.isShare) {

        return [YLCFactory createImageBarButtonWithImageName:@"web_share" selector:@selector(share) target:self];
    }
    return nil;
}
- (void)share{
    [YLCHUDShow showShareHUDWithContent:self.shareContent shareLink:self.shareUrl];
}
- (void)close{
    if (self.isModel) {
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}
- (void)goBack {
    if ([webContentView canGoBack]) {
        [webContentView goBack];
    }else
    {
        if (self.isModel) {
            [self dismissViewControllerAnimated:YES
                                     completion:^{
                                         
                                     }];
        }else {
            [self.navigationController popViewControllerAnimated:YES];
        }
        
    }
}

//#pragma mark -
//#pragma mark UIWebViewDelegate
//
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    NSURL *url = request.URL;
    
    NSLog(@"%@",url.absoluteString);
//    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
//
//    NSURLSessionDataTask *task = [session dataTaskWithRequest:request];
//    
//    [task resume];
//    NSString *url = [[request URL] parameterString];
    
    
    
    return YES;
}
//- (void)URLSession:(NSURLSession *)session
//didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
// completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
//{
//    //AFNetworking中的处理方式
//    NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
//    __block NSURLCredential *credential = nil;
//    //判断服务器返回的证书是否是服务器信任的
//    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
//        credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
//        /*disposition：如何处理证书
//         NSURLSessionAuthChallengePerformDefaultHandling:默认方式处理
//         NSURLSessionAuthChallengeUseCredential：使用指定的证书    NSURLSessionAuthChallengeCancelAuthenticationChallenge：取消请求
//         */
//        if (credential) {
//            disposition = NSURLSessionAuthChallengeUseCredential;
//        } else {
//            disposition = NSURLSessionAuthChallengePerformDefaultHandling;
//        }
//    } else {
//        disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
//    }
//    //安装证书
//    if (completionHandler) {
//        completionHandler(disposition, credential);
//    }
//}
//// 接收到服务器的响应
//- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
//{
//    NSLog(@"didReceiveResponse");
//    completionHandler(NSURLSessionResponseAllow);
//}
//// 接收到服务器返回的数据
//- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
//{
//    NSLog(@"didReceiveData");
//}
//// 请求完毕
//- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
//{
//    NSLog(@"didCompleteWithError");
//}
//
//- (void)webViewDidStartLoad:(UIWebView *)webView {
//
//}
//
//- (void)webViewDidFinishLoad:(UIWebView *)webView {
//    // 禁用用户选择
//    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
//
//    // 禁用长按弹出框
//    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];
//}
//
//- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
//
//}
#pragma mark NJKWebViewProgressDelegate
-(void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress
{
    if (progress == 0.0) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
        progressView.progress = 0;
        [UIView animateWithDuration:0.27 animations:^{
            progressView.alpha = 1.0;
        }];
    }
    if (progress == 1.0) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        [UIView animateWithDuration:0.27 delay:progress - progressView.progress options:0 animations:^{
            progressView.alpha = 0.0;
        } completion:nil];
    }
    
    [progressView setProgress:progress animated:NO];
    
}
- (NSString *)title {
    if (!JK_IS_STR_NIL(self.navTitle)) {
        return self.navTitle;
    }
    
    return @"";
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
